package cn.jinhaze.service.impl;

import cn.jinhaze.entity.ObjectData;
import cn.jinhaze.entity.PageResult;
import cn.jinhaze.entity.ResultData;
import cn.jinhaze.mapper.CoreMapper;
import cn.jinhaze.service.ICoreService;
import cn.jinhaze.utils.HttpsUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class CoreServiceImpl extends ServiceImpl<CoreMapper, ObjectData> implements ICoreService{

    private final RedisTemplate redisTemplate;
    
    private final MongoTemplate mongoTemplate;
    
    private final CoreMapper coreMapper;

    @Override
    @Transactional
    public int process(int pageNum, int pageSize) throws Exception {
        ResultData resData = execute(pageNum, pageSize);
        String content = resData.getContent();
        PageResult<ObjectData> pageResult = JSON.parseObject(content, PageResult.class);
        List<ObjectData> saveList = pageResult.getList();
        log.info("抓取到{}条数据", saveList.size());

        redisTemplate.opsForList().leftPushAll("data", saveList);

        // CoreServiceImpl thisObj = (CoreServiceImpl)AopContext.currentProxy();
        // thisObj.saveBatch(saveList, 500);

        return saveList.size();
    }

    @Override
    public List<ObjectData> getMySQL(Integer pageNum, Integer pageSize) {
        return coreMapper.page((pageNum - 1) * pageSize, pageSize);
    }

    @Override
    public List<ObjectData> getMongo(Integer pageNum, Integer pageSize) {
        Query query = new Query();
        query.skip((long) (pageNum - 1) * pageSize).limit(pageSize);
        return mongoTemplate.find(query, ObjectData.class);
    }

    private ResultData execute(int pageNum, int pageSize) throws Exception {
        CloseableHttpClient httpClient = HttpsUtils.getHttpClient();
        HttpPost httpPost = new HttpPost("https://pfsc.agri.cn/api/priceQuotationController/pageList");
        HttpsUtils.setCommonHeaders(httpPost);
        httpPost.setEntity(new StringEntity("{\"pageNum\":" + pageNum + ",\"pageSize\":" + pageSize + "}"));
        CloseableHttpResponse response = httpClient.execute(httpPost);
        return JSON.parseObject(EntityUtils.toString(response.getEntity()), ResultData.class);
    }

}
